package com.sugon.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AuthCheck;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.LoginUser;
import com.sugon.entity.*;
import com.sugon.modules.device.model.vo.DevRepairExceptionParam;
import com.sugon.modules.mold.consts.MoldPmTicketProgressConst;
import com.sugon.modules.mold.consts.MoldReplacePartProgress;
import com.sugon.modules.mold.model.vo.BaseRepairRecordParamVO;
import com.sugon.modules.mold.model.vo.MoldCallRepairParam;
import com.sugon.modules.mold.service.IMoldRepairRecordManager;
import com.sugon.modules.sys.model.vo.PickerModel;
import com.sugon.modules.sys.utils.FaultTypeTreeNodeUtils;
import com.sugon.service.*;
import com.sugon.util.ApiBaseAction;
import com.sugon.util.ApiPageUtils;
import com.sugon.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模具维修工单接口
 *
 * @author YuXD
 * @since 2020-11-23 17:31
 */
@Api(tags = "模具维修工单接口")
@RestController
@RequestMapping("/api/v1/moldTicket")
public class MoldRepairApiController extends ApiBaseAction {

    @Autowired
    private FaultTypeService faultTypeService;
    @Autowired
    private IMoldRepairRecordManager moldRepairRecordManager;
    @Autowired
    private ModuleRepairRocordService moduleRepairRocordService;
    @Autowired
    private ModuleArchivesService moduleArchivesService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private ModuleReplacePartService moduleReplacePartService;

    @AuthCheck
    @ApiOperation(value = "浇筑/压铸组长模具故障报修")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moduleCode", value = "模具编码", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "devId", value = "设备ID", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "faultCon", value = "问题描述", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/callRepair")
    public ApiResult<String> callRepair(@ApiIgnore @LoginUser SysUserEntity loginUser, @Validated @RequestBody MoldCallRepairParam callRepairParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        // 校验模具是否存在
        ModuleArchivesEntity moduleArchives = moduleArchivesService.queryObject(callRepairParam.getMoldId());
        if (moduleArchives == null) {
            return apiResult.failMsg("模具不存在，请确认！");
        }
        // 校验设备是否存在
        DeviceInfoEntity device = deviceInfoService.queryObject(callRepairParam.getDevId());
        if (device == null) {
            return apiResult.failMsg("设备信息不存在！");
        }
        if (device.getIsModuleRelated() != 1) {
            return apiResult.failMsg("当前设备尚未关联模具，请确认！");
        }
        // 获取故障信息
        FaultTypeEntity faultType = faultTypeService.queryObject(callRepairParam.getFaultType());
        if (faultType == null) {
            return apiResult.failMsg("模具故障信息不存在！");
        }
        // 构建维修工单基础信息
        ModuleRepairRocordEntity moduleRepairRocord = new ModuleRepairRocordEntity();
        BeanUtil.copyProperties(callRepairParam, moduleRepairRocord);
        moduleRepairRocord.setWorkshop(moduleArchives.getSubShop());
        moduleRepairRocord.setReport(loginUser.getNickName());
        moduleRepairRocord.setFaultCode(faultType.getFaultCode());
        moduleRepairRocord.setFaultDesc(faultType.getTypeName());
        return moldRepairRecordManager.callRepair(moduleRepairRocord) ? apiResult.succMsg("报修成功！") : apiResult.failMsg("报修失败，请稍后重试");
    }

    @AuthCheck
    @ApiOperation(value = "获取模具紧急维护工单列表API", notes = "返回未完成状态的工单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "Integer", required = true)
    })
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResult<ApiPageUtils> getDevMaintenWorkList(@ApiIgnore @LoginUser SysUserEntity loginUser,
                                                         @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit
    ) {
        ApiResult<ApiPageUtils> apiResult = new ApiResult<>();
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("limit", limit);
        params.put("sidx", "REPAIR_DATE");
        params.put("order", "DESC");
        // 生产组长、模修工只可以看自己的，否则看整个部门的
        if (loginUser.getLeader() != 1) {
            params.put("filterSql", " AND '" + loginUser.getUserId() + "' IN(MRR.ORDER_EXECUTE_USER ,MRR.REPORT) AND STATUS < 5 ");
        } else {
            params.put("filterSql", " AND MRR.WORKSHOP = '" + loginUser.getWorkShopId() + "' AND STATUS < 5");
        }
        //查询列表数据
        Query map = new Query(params);
        List<ModuleRepairRocordEntity> moldRepairRecords = moduleRepairRocordService.queryList(map);
        int total = moduleRepairRocordService.queryTotal(map);
        ApiPageUtils pageUtil = new ApiPageUtils(moldRepairRecords, total, map.getLimit(), map.getPage());
        return apiResult.success(pageUtil);
    }


    @AuthCheck
    @ApiOperation(value = "模具紧急维护工单详情查询API")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "String", required = true)
    @RequestMapping(value = "detail", method = RequestMethod.POST)
    public ApiResult<ModuleRepairRocordEntity> getDetailById(@RequestParam(value = "id") String id) {
        ApiResult<ModuleRepairRocordEntity> apiResult = new ApiResult<>();
        return apiResult.success(moduleRepairRocordService.queryObject(id));
    }

    @AuthCheck
    @ApiOperation("维修工确认开始维修")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "维修工单ID", paramType = "query", dataType = "String", required = true),
    })
    @RequestMapping("/startRepair")
    public ApiResult<String> startRepair(@ApiIgnore @LoginUser SysUserEntity loginUser, @RequestParam String id) {
        ApiResult<String> apiResult = new ApiResult<>();
        ModuleRepairRocordEntity moldRepairTicket = moduleRepairRocordService.queryObject(id);
        if (moldRepairTicket == null) {
            return apiResult.failMsg("工单信息不存在，请确认！");
        }
        // 校验工单状态
        if (moldRepairTicket.getStatus() != MoldPmTicketProgressConst.DISPATCH) {
            return apiResult.failMsg("只能确认开始维修处于[待派工]状态的工单！");
        }
        moldRepairTicket.setOrderExecuteUser(loginUser.getUserId());
        return moldRepairRecordManager.confirmRepair(moldRepairTicket) ? apiResult.success() : apiResult.fail();
    }

    @AuthCheck
    @ApiOperation("维修工完成维修API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "维修工单ID", paramType = "query", dataType = "String", required = true),
    })
    @RequestMapping("/completeRepair")
    public ApiResult<String> completeRepair(@ApiIgnore @LoginUser SysUserEntity loginUser, @RequestParam String id) {
        ApiResult<String> apiResult = new ApiResult<>();
        ModuleRepairRocordEntity moldMaintenanceTicket = moduleRepairRocordService.queryObject(id);
        if (moldMaintenanceTicket == null) {
            return apiResult.failMsg("工单信息不存在，请确认！");
        }
        // 校验工单状态
        if (moldMaintenanceTicket.getStatus() != MoldPmTicketProgressConst.START_REPAIR) {
            return apiResult.failMsg("只可以完成处于[维修中]的工单！");
        }
        return moldRepairRecordManager.completeRepair(moldMaintenanceTicket) ? apiResult.success() : apiResult.fail();
    }

    @AuthCheck
    @ApiOperation("完善维修记录APi")
    @RequestMapping("/addRepairRecord")
    public ApiResult<String> save(@ApiIgnore @LoginUser SysUserEntity loginUser, @Validated @RequestBody BaseRepairRecordParamVO<ModuleRepairRocordEntity> repairRecordParam, BindingResult bindingResult) {
        ApiResult<String> result = new ApiResult<>();
        // 校验维修工单是否存在
        String maintenRecordId = repairRecordParam.getTicketId();
        ModuleRepairRocordEntity moldMaintenanceTicket = moduleRepairRocordService.queryObject(maintenRecordId);
        if (moldMaintenanceTicket == null) {
            return result.failMsg("工单信息不存在，请确认！");
        }
        // 模具ID必填
        ModuleArchivesEntity mold = moduleArchivesService.queryObject(repairRecordParam.getMoldId());
        if (mold == null) {
            return result.failMsg("模具不存在，请确认！");
        }
        moldMaintenanceTicket.setMoldId(repairRecordParam.getMoldId());
        moldMaintenanceTicket.setModuleNo(mold.getModuleNo());
        repairRecordParam.setTicket(moldMaintenanceTicket);
        if (StrUtil.isEmpty(moldMaintenanceTicket.getOrderExecuteUser())) {
            moldMaintenanceTicket.setOrderExecuteUser(loginUser.getUserId());
        }
        return moldRepairRecordManager.addRepairRecord(repairRecordParam) ? result.success() : result.fail();
    }

    @AuthCheck
    @ApiOperation(value = "异常上报API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "repairTicketId", value = "维修工单ID", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excepCon", value = "异常现象", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excepDescr", value = "问题描述", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "advice", value = "建议", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/addException")
    public ApiResult<String> addException(@ApiIgnore @LoginUser SysUserEntity loginUser, @Validated DevRepairExceptionParam devRepairExceptionParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        // 校验巡检项是否存在
        ModuleRepairRocordEntity moldMaintenanceRecord = moduleRepairRocordService.queryObject(devRepairExceptionParam.getRepairTicketId());
        if (moldMaintenanceRecord == null) {
            return apiResult.failMsg("维修工单不存在!");
        }
        devRepairExceptionParam.setPlanExecutorId(loginUser.getUserId());
        return moldRepairRecordManager.addDevMaintenanceException(devRepairExceptionParam) ? apiResult.success() : apiResult.fail();
    }

    @ApiOperation("获取模具故障类别API")
    @RequestMapping("/getFaultTypes")
    public ApiResult<List<PickerModel>> getFaultTypes() {
        ApiResult<List<PickerModel>> result = new ApiResult<>();
        List<PickerModel> faultTypeList = new ArrayList<>();
        List<FaultTypeEntity> faultTypes = faultTypeService.queryList(null);
        // 整合数据到一起
        for (FaultTypeEntity faultType : faultTypes) {
            faultTypeList.add(new PickerModel(faultType));
        }
        // 构建设备组织树
        FaultTypeTreeNodeUtils treeNodeUtils = new FaultTypeTreeNodeUtils(faultTypeList);
        PickerModel root = treeNodeUtils.generateTree("71");
        return result.success(root.getChildren());
    }

    @RequestMapping("/commitApprove")
    public ApiResult<String> commitApprove(@RequestParam String id) {
        ApiResult<String> apiResult = new ApiResult<>();
        // 校验是否存在
        ModuleRepairRocordEntity moduleRepairRocord = moduleRepairRocordService.queryObject(id);
        if (moduleRepairRocord == null) {
            return apiResult.failMsg("模具维修工单不存在，请确认!");
        }
        // 校验是否审核中
        int progress = moduleRepairRocord.getProgress();
        if (progress != MoldReplacePartProgress.NEW && progress != MoldReplacePartProgress.NOT_PASSED) {
            return apiResult.failMsg("模具维修工单审核中或已通过审核，无需重复提交!");
        }
        // 校验是否已填充内容e
        List<ModuleReplacePartEntity> list = moduleReplacePartService.queryList(moduleRepairRocord.getMoldId(), 1, moduleRepairRocord.getRepairCode());
        if (CollectionUtil.isEmpty(list)) {
            return apiResult.failMsg("请在添加换件记录后再提交审核！");
        }
        return moldRepairRecordManager.commitApprove(moduleRepairRocord) ? apiResult.success() : apiResult.failMsg("提交失败，请稍后重试!");
    }

}




